package com.kqb.service.impl;

import com.kqb.common.domain.AjaxResult;
import com.kqb.mapper.DepartmentMapper;
import com.kqb.pojo.Department;
import com.kqb.pojo.dto.DepartmentDto;
import com.kqb.service.IDepartmentService;
import com.kqb.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author 杉果树皮
 * @date 2025/2/18 14:01
 * @description: 部门
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public AjaxResult save(DepartmentDto departmentDTO) {
        Department department = new Department();
        if (!"".equals(departmentDTO.getPName())) {
            Department department1 = departmentMapper.selectByName(departmentDTO.getPName());
            if (department1 == null) {
                return AjaxResult.error("添加失败,父部门不存在");
            } else {
                department.setParentId(department1.getId());
            }
        }

        department.setName(departmentDTO.getName());
        int save = departmentMapper.save(department);
        return save == 0 ? AjaxResult.error(201, "添加部门失败") : AjaxResult.success("添加部门成功");
    }

    @Override
    public AjaxResult deleteById(Integer id) {
        if (departmentMapper.selectByParentId(id) != 0) {
            return AjaxResult.error("存在子部门，不允许删除");
        }
        return departmentMapper.delete(id) == 0 ? AjaxResult.error("删除部门失败") : AjaxResult.success("删除部门成功");
    }

    @Override
    public AjaxResult update(Department department) {
        Department select = departmentMapper.select(department.getId());
        if (select == null) {
            return AjaxResult.error("修改部门失败，没有对应的部门");
        }
        return departmentMapper.update(department) == 0 ? AjaxResult.error("修改部门失败") : AjaxResult.success("修改部门成功");
    }

    @Override
    public AjaxResult selectByPage(DepartmentDto departmentDTO) {
        List<Department> query = departmentMapper.queryByPage(departmentDTO);
        //删除分页功能 但给前端返回有相关信息
        return AjaxResult.success("查询部门成功", query);

    }

    @Override
    public AjaxResult selectAll() {
        return AjaxResult.success(departmentMapper.selectAll());
    }


}
